import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, Button, Typography, Form, Input, message, Spin, Avatar, Select, Upload, DatePicker } from 'antd';
import { UserOutlined, LeftOutlined, MailOutlined, EnvironmentOutlined, UploadOutlined } from '@ant-design/icons';
import styled from 'styled-components';
import api, { API_BASE_URL } from '../services/api'; // 导入 api 和 API_BASE_URL
import { User } from '../store/slices/userSlice'; // 导入 User 类型
import type { UploadProps } from 'antd'; // 导入 UploadProps 类型
import { RcFile, UploadChangeParam, UploadFile } from 'antd/es/upload/interface'; // 导入必要的类型
import dayjs, { Dayjs } from 'dayjs';
import { Link } from 'react-router-dom'; // 导入 Link 组件

const { Title, Text } = Typography;
const { Option } = Select;

const StyledCard = styled(Card)`
    margin: 0 auto;
    max-width: 600px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
`;

// 计算年龄的函数
const calculateAge = (birthDate: Date): number => {
    const today = new Date();
    let age = today.getFullYear() - birthDate.getFullYear();
    const monthDiff = today.getMonth() - birthDate.getMonth();

    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }

    return age;
};

// 计算星座的函数
const calculateZodiacSign = (birthDate: Date): string => {
    const month = birthDate.getMonth() + 1;
    const day = birthDate.getDate();

    if ((month === 3 && day >= 21) || (month === 4 && day <= 19)) return '白羊座';
    if ((month === 4 && day >= 20) || (month === 5 && day <= 20)) return '金牛座';
    if ((month === 5 && day >= 21) || (month === 6 && day <= 21)) return '双子座';
    if ((month === 6 && day >= 22) || (month === 7 && day <= 22)) return '巨蟹座';
    if ((month === 7 && day >= 23) || (month === 8 && day <= 22)) return '狮子座';
    if ((month === 8 && day >= 23) || (month === 9 && day <= 22)) return '处女座';
    if ((month === 9 && day >= 23) || (month === 10 && day <= 23)) return '天秤座';
    if ((month === 10 && day >= 24) || (month === 11 && day <= 22)) return '天蝎座';
    if ((month === 11 && day >= 23) || (month === 12 && day <= 21)) return '射手座';
    if ((month === 12 && day >= 22) || (month === 1 && day <= 19)) return '摩羯座';
    if ((month === 1 && day >= 20) || (month === 2 && day <= 18)) return '水瓶座';
    return '双鱼座';
};

const ProfileEditPage: React.FC = () => {
    const navigate = useNavigate();
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(true);
    const [submitting, setSubmitting] = useState(false);
    const [userData, setUserData] = useState<User | null>(null);
    const [fileList, setFileList] = useState<UploadFile[]>([]);

    useEffect(() => {
        const fetchUserProfile = async () => {
            try {
                setLoading(true);
                const token = localStorage.getItem('userToken');
                if (!token) {
                    message.error('未认证，请先登录。');
                    navigate('/login');
                    return;
                }

                const response = await api.auth.getUserProfile(token);

                if (response.success && response.user) {
                    const fetchedUser = response.user;
                    setUserData(fetchedUser);

                    // 在获取到用户数据后，使用 setFieldsValue 设置所有字段
                    // 这应该会填充 disabled 的邮箱字段
                    form.setFieldsValue({
                        ...fetchedUser,
                        // 确保 birthDate 是 Dayjs 对象，以便 DatePicker 正确显示
                        birthDate: fetchedUser.birthDate ? dayjs(fetchedUser.birthDate) : undefined,
                    });

                    // 使用 fetchedUser 初始化 fileList
                    if (fetchedUser.avatar) {
                        setFileList([
                            {
                                uid: '-1',
                                name: 'existing_avatar.png',
                                status: 'done',
                                url: `${API_BASE_URL.replace('/api', '')}${fetchedUser.avatar}`,
                            },
                        ]);
                    }
                } else {
                    message.error(response.message || '获取用户资料失败');
                }
            } catch (error) {
                console.error('Error fetching user profile:', error);
                message.error('获取用户资料失败');
            } finally {
                setLoading(false);
            }
        };

        fetchUserProfile();
    }, [form, navigate]); // Keep form in dependency array if setFieldsValue is called inside

    const handleFileChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
        // 根据 Upload 中的 maxCount={1}，限制 fileList 中只有一个文件
        setFileList(newFileList.slice(-1));
    };

    // 处理生日变化 (更新 userData 状态)
    const handleBirthDateChange = (date: Dayjs | null) => {
        setUserData(prevUserData => {
            if (!prevUserData) return null;
            const birthDateString = date ? date.toISOString().split('T')[0] : undefined;
            // 在这里根据新的 birthDate 更新 age 和 zodiacSign
            const age = date ? calculateAge(date.toDate()) : undefined;
            const zodiacSign = date ? calculateZodiacSign(date.toDate()) : undefined;

            // 同时更新 form 的对应字段，以便立即反映在 UI 上
            form.setFieldsValue({
                birthDate: date,
                age: age,
                zodiacSign: zodiacSign,
            });

            return {
                ...prevUserData,
                birthDate: birthDateString,
                age: age,
                zodiacSign: zodiacSign,
            };
        });
    };

    const onFinish = async (values: any) => {
        setSubmitting(true);
        try {
            const submissionData: Partial<Omit<User, 'interestTags'>> = {};

            // 明确地从 values 中取出需要更新的字段并进行类型处理 (排除 email)
            if (values.username !== undefined && values.username !== null) submissionData.username = values.username;
            if (values.gender !== undefined && values.gender !== null) submissionData.gender = values.gender;
            if (values.location !== undefined && values.location !== null) submissionData.location = values.location;
            if (values.bio !== undefined && values.bio !== null) submissionData.bio = values.bio;
            if (values.age !== undefined && values.age !== null) submissionData.age = values.age;

            // 特殊处理 birthDate
            if (values.birthDate !== undefined && values.birthDate !== null && values.birthDate instanceof dayjs) {
                submissionData.birthDate = (values.birthDate as dayjs.Dayjs).toISOString().split('T')[0];
                // 根据 birthDate 计算并更新 zodiacSign
                // 注意：zodiacSign 属性也存在于 User 类型中，可以安全地添加到 submissionData
                submissionData.zodiacSign = calculateZodiacSign((values.birthDate as dayjs.Dayjs).toDate());
            } else if (values.birthDate === null) {
                // 如果 birthDate 被清空，则设置为 undefined
                submissionData.birthDate = undefined;
                // 清空相关的 zodiacSign 和 age
                submissionData.zodiacSign = undefined;
                submissionData.age = undefined;
            }

            // 处理头像上传逻辑
            if (fileList.length > 0 && fileList[0].originFileObj) {
                // TODO: 实现头像上传并将 URL 包含在 submissionData 中
                // 当头像上传成功后，获取到 URL，然后将其添加到 submissionData 中
                // submissionData.avatar = avatarUrl;
            } else if (fileList.length === 0 && userData?.avatar) {
                // 如果移除了头像，将 avatar 设置为 undefined
                submissionData.avatar = undefined;
            }

            const token = localStorage.getItem('userToken');
            if (!token) {
                message.error('未认证，请先登录。');
                navigate('/login');
                return;
            }

            // 发送更新请求
            const response = await api.auth.updateUserProfile(token, submissionData);

            if (response.success && response.user) {
                message.success('资料更新成功');
                // 可选：更新 Redux store 中的用户资料
                // dispatch(updateProfile(response.user)); 
                navigate('/profile'); // Redirect to profile page
            } else {
                message.error(response.message || '更新失败');
            }
        } catch (error) {
            console.error('Update profile error:', error);
            message.error('更新失败');
        } finally {
            setSubmitting(false);
        }
    };

    if (loading) {
        return <Spin size="large"></Spin>;
    }

    if (!userData && !loading) {
        // Handle case where user data couldn't be loaded
        return (
            <div style={{ textAlign: 'center', marginTop: '50px' }}>
                <Title level={4}>无法加载用户资料</Title>
                <Button type="primary" onClick={() => navigate(-1)}>返回</Button>
            </div>
        );
    }

    return (
        <div>
            <StyledCard title={
                <div style={{ display: 'flex', alignItems: 'center' }}>
                    <LeftOutlined
                        style={{ marginRight: 16, cursor: 'pointer' }}
                        onClick={() => navigate(-1)}
                    />
                    <Title level={4} style={{ margin: 0 }}><UserOutlined style={{ marginRight: 8 }} />编辑资料</Title>
                </div>
            }>
                <Form
                    form={form}
                    layout="vertical"
                    onFinish={onFinish}
                    // initialValues 仍然可以用于初次渲染，但 setFieldsValue 会在数据加载后覆盖
                    initialValues={userData ? {
                        ...userData,
                        birthDate: userData.birthDate ? dayjs(userData.birthDate) : undefined,
                    } : undefined}
                >
                    {/* 头像上传项 */}
                    <Form.Item label="头像">
                        <Upload
                            listType="picture-card"
                            fileList={fileList}
                            onChange={handleFileChange}
                            beforeUpload={() => false} // 阻止自动上传
                            maxCount={1} // 只允许一个文件
                        >
                            {fileList.length === 0 && (
                                <div>
                                    <UploadOutlined />
                                    <div style={{ marginTop: 8 }}>选择图片</div>
                                </div>
                            )}
                        </Upload>
                    </Form.Item>

                    {/* 用户名项 */}
                    <Form.Item
                        label="用户名"
                        name="username"
                        rules={[{ required: true, message: '请输入用户名' }]}
                    >
                        <Input />
                    </Form.Item>

                    {/* 邮箱项 - 不再是 Form 控制的字段 */}
                    <Form.Item label="邮箱" > {/* 移除 name="email" 和 rules */}
                        <Input disabled value={userData?.email} /> {/* 直接设置值 */} {/* 邮箱不可编辑 */}
                    </Form.Item>

                    {/* 个人简介项 */}
                    <Form.Item label="个人简介" name="bio">
                        <Input.TextArea rows={3} />
                    </Form.Item>

                    {/* 性别项 */}
                    <Form.Item label="性别" name="gender">
                        <Select placeholder="请选择性别">
                            <Option value="male">男</Option>
                            <Option value="female">女</Option>
                            <Option value="other">其他</Option>
                        </Select>
                    </Form.Item>

                    {/* 出生日期项 */}
                    <Form.Item label="出生日期" name="birthDate">
                        <DatePicker style={{ width: '100%' }} onChange={handleBirthDateChange} />
                    </Form.Item>

                    {/* 年龄项 - 仅显示 */}
                    <Form.Item label="年龄" name="age">
                        <Input disabled />
                    </Form.Item>

                    {/* 星座项 - 仅显示 */}
                    <Form.Item label="星座" name="zodiacSign">
                        <Input disabled />
                    </Form.Item>

                    {/* 位置项 */}
                    <Form.Item label="位置" name="location">
                        <Input />
                    </Form.Item>

                    <Form.Item>
                        <Button type="primary" htmlType="submit" loading={submitting}>
                            保存修改
                        </Button>
                    </Form.Item>
                </Form>
            </StyledCard>
        </div>
    );
};

export default ProfileEditPage; 